package io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;

import org.bushe.swing.event.EventBus;

import constants.Events;

import model.i.IState;

/**
 * Responsible for deserialization of IState objects
 */
public class Load {

    IState s;

    /**
     * Inflates the IState object from a file
     * @param file the file to deserialize
     * @return the deserialized file
     * @throws ClassNotFoundException if given a bad file path (issue50)
     */
    public void readFromFile(String file){

        ObjectInputStream inputStream = null;
        Object content = null;

        try{
            inputStream = new ObjectInputStream(new FileInputStream(file));
            content = inputStream.readObject();

        } catch (FileNotFoundException ex){
            EventBus.publish(Events.ERROR.toString(), "File not found!");
        } catch (IOException ex){
            EventBus.publish(Events.ERROR.toString(), "Load failed!");
        } catch (ClassNotFoundException e) {
            EventBus.publish(Events.ERROR.toString(), "Class not found!");
        } finally {
            try{
                if(inputStream != null){
                    inputStream.close();
                }
            } catch (IOException ex){
                ex.printStackTrace();
            }
        }

        IState state = (IState) content;

        s = state;
    } //ReadFromFile

    public IState getLoadedState(){
        return s;
    }
}
